using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using System.Globalization;
using System.Web.Configuration;
using log4net;
using System.Text;
using MedicinaMuncii.UI.Mvc.Properties;

namespace MedicinaMuncii.UI.Mvc.Controllers
{
    /// <summary>
    /// Base class for all controllers in the application
    /// Handles functionality common to all views (like providing data for masterpage, etc.)
    /// </summary>
    public abstract class BaseController : Controller
    {
        #region Fields
        /// <summary>
        /// Logger
        /// </summary>
        protected readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion

        #region Contructor
        /// <summary>
        /// Constructor
        /// </summary>
        internal BaseController()
        {
            InitializeCulture();
            InitializeMaster();
        }
        #endregion

        #region Protected Methods
        /// <summary>
        /// If the provided value is empty, the value is tried to be retrieved from the cookie with the specified name
        /// In case the provided value alraedy has a valid value, that value is stored in a cookie with the specified name
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        protected void HandleCookieValue(string key, ref string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                // Load value from cookie
                if (ControllerContext.HttpContext.Request.Cookies[key] != null)
                {
                    value = ControllerContext.HttpContext.Request.Cookies[key].Value;
                }
            }
            else
            {
                // Save value to cookie
                HttpCookie cookie = new HttpCookie(key, value.ToString());
                cookie.Expires = DateTime.Now.AddYears(100);
                ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
        }
        #endregion

        #region Helper Methods
        private void InitializeCulture()
        {
            CultureInfo currentCulture = CultureInfo.CreateSpecificCulture(Settings.Default.DefaultLanguage);
            Thread.CurrentThread.CurrentCulture = currentCulture;
            Thread.CurrentThread.CurrentUICulture = currentCulture;
        }

        private void InitializeMaster()
        {
            ViewData["ApplicationName"] = Resources.Global.ApplicationName;
        }
        #endregion
    }
}
